package com.rrd.hive.udf;

import java.security.MessageDigest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;


public class Md5UDF extends UDF{
	private static final char[] dictionary = "yourdxinab".toCharArray();
	
	public Text evaluate(String mobile) {
		Text text = new Text();
		if(mobile==null || mobile.equals("")){
			return null;
		}
		String s=genratePhoneSummary(mobile);
		if(s==null){
			return null;
		}else{
			text.set(s);	
		}
		
		return text;
	}
	/**
     * MD5加密
     *
     * @param str
     * @return
     */
    public static String getMD5(String str) {
    	  int number=0;
    	  String s=null;
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            StringBuffer buffer = new StringBuffer();
            for (byte b : md.digest(str.getBytes())) {
                 number = b & 0xff;
                 s = Integer.toHexString(number);
                if (s.length() == 1) {
                    buffer.append("0");
                }
                buffer.append(s);
            }
            return buffer.toString().toUpperCase();
        } catch (Exception e) {
        	System.out.println("MD5加密失败，失败原因：{}");
             e.printStackTrace();
            return null;
        }
    }

    private static String mobileTostr(String mobile) {
        StringBuffer sb = new StringBuffer();
        char[] charArray = mobile.toCharArray();
        for (char c : charArray) {
            sb.append(dictionary[c - '0']);
        }
        return sb.toString();
    }

    /**
     * 加密规则，先将手机号转成字典码字符串，再做MD5加密后
     *
     * @param phone
     * @return
     */
    public static String genratePhoneSummary(String phone) {
        if (StringUtils.isEmpty(phone)) {
            return null;
        }
        if (phone.length() != 11 || !NumberUtils.isDigits(phone)) {
            return null;
        }
        return getMD5(mobileTostr(phone));
    }
}
